﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ShoppingApp2.DAL;
using ShoppingApp2.Common.Models;
using ShoppingApp2.Common;
using System.Configuration;

namespace ShoppingApp2.BLL
{
    public class UsersBll
    {
        UsersDAL _users;
        Transaction transaction;
        
        public UsersBll()
        {
            transaction = new Transaction(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            _users = new UsersDAL(transaction);
        }

        /// <summary>
        /// Creates user in proper tables in db
        /// </summary>
        public void CreateUser(UserModelExt user)
        {
            try
            {
                transaction.BeginTransaction();
                
                // Set of operations
                int? userId = _users.CreateUser(user);

                // Create token in tokens history table
                if (userId.HasValue)
                    _users.CreateTokenInHistory(userId.Value, Guid.NewGuid().ToString());
                else
                    throw new ArgumentNullException("UserId was null when trying to create token history entry");

                transaction.Commit();
            }
            catch
            {
                transaction.RollBack();
                throw;
            }
           
        }

    }
}